package com.lleice.common.configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * mvc配置
 * @author lizihao
 */
@Configuration
public class MyWebMvcConfiguration implements  WebMvcConfigurer{

    @Bean
    CrosHandlerInterceptor getCrosHandlerInterceptor() {
        return new CrosHandlerInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getCrosHandlerInterceptor()).addPathPatterns("/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    	//监控内置ui
        registry.addResourceHandler("/monitor/**").addResourceLocations("classpath:/META-INF/resources/monitor/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

    class CrosHandlerInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            //允许跨域
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", request.getMethod());
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Allow-Headers"));

            //跨域时首先发一个OPTIONS请求检验后台是否能跨域，我们这里直接返回正常状态
            if (request.getMethod().equals(HttpMethod.OPTIONS.name())) {
                response.setStatus(HttpStatus.OK.value());
                response.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT,OPTIONS");
                response.setHeader("Access-Control-Allow-Headers", "Cache-Control, Origin, X-Requested-With," +
                        "Content-Type,catalogType,Accept,Authorization,token,Content-Disposition,Content-Length,Date,X-Request-Id");
                return true;
            }

            return super.preHandle(request, response, handler);
        }
    }

}
